import axios from 'axios';
import { getEnv } from './envConfig.js';

const http = axios.create({
  timeout: 1000 * 10,
  retryDelay: 1000 * 10,
})


http.interceptors.request.use((config) => {
  // if (getEnv('ISOPENPROXY')) {
  //   config.httpsAgent = agent
  // }
  if (config.method.toLocaleLowerCase() === 'get' && config.parmas && JSON.stringify(config.params) !== '{}') {
    const obj = config.params
    for (const key in obj) {
      if (Object.hasOwnProperty.call(obj, key)) {
        const val = obj[key];
        config.url += key + '=' + val + '&'
      }
    }
    config.url += `&time=${new Date().getTime()}`
  }
  return config
}, (err) => {
  return Promise.reject(err)
})

http.interceptors.response.use((response, err) => {
  if (response.status === 200) {
    return response.data
  }

  const { config, code, message } = err

  if (code === 'ECONNABORTED' || message === 'Network Error') {
    // 请求超时

    return new Promise(resolve => {
      setTimeout(async _ => {
        resolve(await http.request(config))
      }, defaultConfig.retryDelay) // 设置发送间隔
    })
  }
}, (err) => {
  return Promise.reject('访问失败:' + err)
})

export default http